#!/bin/bash

# 默认值（可通过环境变量覆盖）
NGINX_ROOT="${NGINX_ROOT:-/usr/share/nginx/html}"

echo "⚙️ 正在配置 Nginx..."

# 确保 Nginx 根目录存在（若未在主脚本中处理）
if [ -e "$NGINX_ROOT" ] && [ ! -d "$NGINX_ROOT" ]; then
    echo "❌ $NGINX_ROOT 存在但不是目录，正在删除..."
    sudo rm -f "$NGINX_ROOT"
fi

if [ ! -d "$NGINX_ROOT" ]; then
    echo "📁 创建 Nginx 静态目录: $NGINX_ROOT"
    sudo mkdir -p "$NGINX_ROOT"
    sudo chown -R $(whoami):$(whoami) "$NGINX_ROOT"
fi

# 写入 Nginx 配置
sudo tee /etc/nginx/nginx.conf > /dev/null << 'EOF'
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    keepalive_timeout  65;

    # Gzip 压缩优化
    gzip  on;
    gzip_types text/plain application/json application/javascript text/css;

    # 请求频率限制
    limit_req_zone $binary_remote_addr zone=frontend:10m rate=10r/s;

    # ========== 用户端 Server ==========
    server {
        listen 80;
        server_name localhost;

        root /usr/share/nginx/html/user;
        index index.html;

        client_max_body_size 5M;

        location / {
            try_files $uri $uri/ /index.html;
            limit_req zone=frontend burst=20 nodelay;
        }

        location /api/ {
            proxy_pass http://localhost:8080/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }

        location ~* ^/(?!api/).+\.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            limit_req zone=frontend burst=5 nodelay;
        }
    }

    # ========== 管理端 Server ==========
    server {
        listen 10000;
        server_name localhost;

        root /usr/share/nginx/html/admin;
        index index.html;

        location / {
            try_files $uri $uri/ /index.html;
            limit_req zone=frontend burst=20 nodelay;
        }

        location /api/ {
            proxy_pass http://localhost:10010/api/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }

        location ~* ^/(?!api/).+\.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            limit_req zone=frontend burst=5 nodelay;
        }
    }
}
EOF

# 测试并重启 Nginx
echo "🔄 正在测试 Nginx 配置..."
sudo nginx -t
if [ $? -eq 0 ]; then
    echo "✅ 配置正确，正在重启 Nginx..."
    sudo systemctl restart nginx
    echo "✅ Nginx 已成功重启"
else
    echo "❌ Nginx 配置错误，请检查 /etc/nginx/nginx.conf"
    exit 1
fi
